<script setup lang="ts">
import type { RoleDetailResult } from "@/api/types";
import { computed, watch } from "vue";
import { $t } from "@/plugins/i18n";
import { useRoleForm } from "../composables";
import { roleFormRules as rules } from "../utils/rules";

interface Props {
    visible?: boolean;
    editData?: RoleDetailResult | null;
}

interface Emits {
    (e: "update:visible", visible: boolean): void;
    (e: "success"): void;
}

const props = withDefaults(defineProps<Props>(), {
    visible: false,
    editData: null,
});

const emit = defineEmits<Emits>();

const { formData, formRef, resetForm, submitLoading, handleSubmit } = useRoleForm();

watch(
    () => props.visible,
    (val) => {
        if (val) {
            resetForm();
            if (props.editData) {
                Object.assign(formData, props.editData);
            }
        }
    },
);

const isEdit = computed(() => !!props.editData);

const dialogTitle = computed(() =>
    isEdit.value ? $t("title.editRole") : $t("title.addRole"),
);

function handleClose() {
    emit("update:visible", false);
}

function handleFormSubmit() {
    handleSubmit(isEdit.value, () => {
        emit("success");
        handleClose();
    });
}
</script>

<template>
    <el-dialog
        :model-value="visible"
        :title="dialogTitle"
        width="520px"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="auto"
            label-position="right"
        >
            <el-form-item :label="$t('label.roleName')" prop="name">
                <el-input
                    v-model.trim="formData.name"
                    :placeholder="$t('placeholder.inputRoleName')"
                />
            </el-form-item>
            <el-form-item :label="$t('label.roleCode')" prop="code">
                <el-input
                    v-model.trim="formData.code"
                    :disabled="isEdit"
                    :placeholder="$t('placeholder.inputRoleCode')"
                />
            </el-form-item>
            <el-form-item :label="$t('label.remark')" prop="remark">
                <el-input
                    v-model.trim="formData.remark"
                    type="textarea"
                    :rows="3"
                    :placeholder="$t('placeholder.inputRemark')"
                    maxlength="200"
                    show-word-limit
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="text-right">
                <el-button @click="handleClose">
                    {{ $t("button.cancel") }}
                </el-button>
                <el-button type="primary" :loading="submitLoading" @click="handleFormSubmit">
                    {{ $t("button.confirm") }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
